package com.ruoyi.business.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.domain.koc.TbKocLevel;
import com.ruoyi.business.domain.koc.TbUser;
import com.ruoyi.business.domain.vo.TbUserImportVO;
import com.ruoyi.business.service.koc.ITbKocLevelService;
import com.ruoyi.business.service.koc.ITbUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.business.SourceTypeEnum;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class UserImportListener extends AnalysisEventListener<TbUserImportVO> implements ExcelListener<TbUserImportVO> {

    private final ITbUserService userService;


    private final String operName;

    private final Boolean isUpdateSupport;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public UserImportListener(Boolean isUpdateSupport) {
        this.userService = SpringUtils.getBean(ITbUserService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }


    @Override
    public void invoke(TbUserImportVO userVo, AnalysisContext context) {
        TbUser tbUser = userService.getOne(Wrappers.lambdaQuery(TbUser.class).eq(TbUser::getMobile, userVo.getMobile()));
        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(tbUser)) {
                tbUser = BeanUtil.toBean(userVo, TbUser.class);
                Long kocLevelId = tbUser.getKocLevelId();
                if (kocLevelId > 0) {
                    ITbKocLevelService tbKocLevelService = SpringUtils.getBean(ITbKocLevelService.class);
                    TbKocLevel tbKocLevel = tbKocLevelService.getById(kocLevelId);
                    tbUser.setKocLevelId(tbKocLevel.getId());
                    tbUser.setKocLevelName(tbKocLevel.getName());
                    tbUser.setIsKoc(Constants.TRUE_1);
                    tbUser.setSourceType(SourceTypeEnum.KOC_EXCEL_IMPORT.getCode());
                    tbUser.setKocLevelTime(new Date());
                } else {
                    tbUser.setIsKoc(Constants.FALSE_0);
                    tbUser.setSourceType(SourceTypeEnum.KOC_EXCEL_IMPORT.getCode());
                }
                tbUser.setFreePoints(0);
                tbUser.setFrozenPoints(0);
                tbUser.setTotalPoints(0);
                tbUser.setId(IdWorker.getId());
                tbUser.setCreateBy(operName);
                userService.save(tbUser);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、手机号 ").append(tbUser.getMobile()).append(" 导入成功");
            } else if (isUpdateSupport) {
                tbUser.setNickname(userVo.getNickname());
                tbUser.setRealName(userVo.getRealName());
                tbUser.setUpdateBy(operName);
                userService.updateById(tbUser);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、手机号 ").append(tbUser.getMobile()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、手机号 ").append(tbUser.getMobile()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、手机号 " + tbUser.getMobile() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<TbUserImportVO> getExcelResult() {
        return new ExcelResult<TbUserImportVO>() {
            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<TbUserImportVO> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
